const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// 配置 Express 以提供静态文件服务
app.use(express.static(__dirname));

io.on('connection', (socket) => {
    console.log('A user connected');

    // 监听用户发送昵称
    socket.on('setNickname', (nickname) => {
        userNicknames[socket.id] = nickname;
        io.emit('userJoined', { nickname, id: socket.id });
    });

    // 监听用户发送消息
    socket.on('chatMessage', (message) => {
        const nickname = userNicknames[socket.id];
        io.emit('newMessage', { nickname, message });
    });

    // 监听用户断开连接
    socket.on('disconnect', () => {
        const nickname = userNicknames[socket.id];
        delete userNicknames[socket.id];
        io.emit('userLeft', { nickname });
    });
});

const port = 3000;
server.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});